use reqwest::Client;
use std::time::Duration;
use url::Url;
use std::sync::Arc;
pub async fn mercury(url: Arc<Url>) -> Result<MercuryOutput, MercuryError> {
    let process_timeout = Duration::from_secs(10);
    let _params = &[("url", url.to_string())];
    let request_url = format!("http://mercury:3000/parser?url={}", url.as_str());
    //request_url.set_port(Some(3000)).map_err(|_| println!("set port error!"));
    println!("{request_url:#?}");
    let output = Client::builder()
        .timeout(process_timeout)
        .build()
        .unwrap()
        .get(request_url)
        .send()
        .await?
        .text()
        .await?;
    println!("{output:?}");

    if let Ok(output) = serde_json::from_str::<MercuryOutput>(&output) {
        println!("{output:?}");
        return Ok(output);
    }
    if let Ok(output_error) = serde_json::from_str::<MercuryOutputError>(&output) {
        println!("{output_error:?}");
        return Err(MercuryError::MercuryError(output_error.messages));
    }

    Err(MercuryError::SerdeError())

    // println!("mercury: {:#?}", output);
    // let output = output?;
    //   output
}
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct MercuryOutput {
    pub title: Option<String>,
    pub content: Option<String>,
    pub author: Option<String>,
    pub date_published: Option<String>,
    pub lead_image_url: Option<Url>,
    pub next_page_url: Option<Url>,
    pub dek: Option<String>,
    pub url: Url,
    pub domain: Option<String>,
    pub excerpt: Option<String>,
    pub word_count: Option<i64>,
    pub direction: Option<String>,
    pub total_pages: Option<i64>,
    pub rendered_pages: Option<i64>,
}
use thiserror::Error;
#[derive(Debug, Error)]
pub enum MercuryError {
    #[error("Parameter url is invalid")]
    InvalidUrl,
    #[error("failed to start mercury process")]
    CommandError(#[from] std::io::Error),
    #[error("Could not parse stderr")]
    ParseResponse,
    #[error("Process timed out")]
    ProcessTimeout,
    // #[error("cannot deserialize json")]
    // SerdeError(#[from] serde_json::Error),
    #[error("cannot deserialize json")]
    SerdeError(),
    #[error("failed to start mercury process")]
    RequestError(#[from] reqwest::Error),
    #[error("failed to start mercury process")]
    ParserError(#[from] url::ParseError),
    #[error("mercury error: {0}")]
    MercuryError(String),
    #[error("")]
    OtherError,
}
#[derive(Debug, Deserialize)]
struct MercuryOutputError {
    error: bool,
    messages: String,
}
